package com.jffccloud.auth.security;

import com.jffccloud.auth.model.SysUser;
import com.jffccloud.auth.service.UserService;
import com.jffccloud.common.model.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
@Service
public class AuthUserDetailService implements UserDetailsService {
    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    UserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser user = userService.findUserByUsername(s);
        if (user == null) {
            throw new BadCredentialsException("用户名不存在或者密码错误");
        }
        Collection<GrantedAuthority> authorities = userService.loadUserAuthorities(user.getUserId());
        SecurityUser u = new SecurityUser(user.getUserId(),user.getUsername(),user.getPassword(),user.getName(),true,authorities);
        return u;
    }
}
